//
//  WBUserAccount.swift
//  新浪微博
//
//  Created by zj on 2017/10/18.
//  Copyright © 2017年 zj. All rights reserved.
//

import UIKit

private let filePath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last! as NSString).appendingPathComponent("useraccount.json")

@objcMembers
class WBUserAccount: NSObject {
    var access_token: String? // = "2.00lFQjVD1TOCdBb75281cd65gBvUzD"
    
    var uid: String?
    var expires_in: TimeInterval = 0 {
        didSet {
            expiresDate = Date.init(timeIntervalSinceNow: expires_in)
        }
    }
    
    var expiresDate: Date?
    
    var screen_name: String?
    var avatar_large: String?
    
    override var description: String {
        return yy_modelDescription()
    }
    
    override init() {
        super.init()
        
        guard let data = NSData.init(contentsOfFile: filePath),
            let dict = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String: AnyObject]else {
            return
        }
        
        // 2.使用字典设置属性值
        // ***
        yy_modelSet(with: dict ?? [:])
        
        // 3.判断 token 是否过期
        // 测试过期日期
        // expiresDate = Date.init(timeIntervalSinceNow: -3600 * 24)
        if expiresDate?.compare(Date()) != .orderedDescending {
            print("账户过期")
            // 清空token
            access_token = nil
            uid = nil
            
            try? FileManager.default.removeItem(atPath: filePath)
        }
    }
    
    func saveAccount() {
        var dict = yy_modelToJSONObject() as? [String: AnyObject]
        
        dict?.removeValue(forKey: "expires_in")
        
        guard let data = try? JSONSerialization.data(withJSONObject: dict ?? [], options: []) else {
                return
        }
        
        (data as NSData).write(toFile: filePath, atomically: true)
        print("用户账户保存成功 \(filePath)")
    }
}
